package cn.yi.boot.shiro.security;

import cn.yi.boot.shiro.UserCons;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import yi.boot.common.security.dto.BaseShiroUser;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class UserCredentialsMatcher extends HashedCredentialsMatcher {

    private Cache<String, AtomicInteger> passwordRetryCache;

    //    /**
//     * 默认重试次数
//     */
//    @Value("${shiro.login.error.retryTimes}")
    @Setter
    private Long retryTimes = 20L;
    //    @Value("${shiro.login.error.cacheName}")
    @Setter
    private String cacheName;
    //    @Autowired
    @Setter
    private CacheManager cacheManager;


    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        passwordRetryCache = cacheManager.getCache(cacheName);
        String username = (String) token.getPrincipal();
        AtomicInteger userAtomicInteger = passwordRetryCache.get(username);
        if (Objects.isNull(userAtomicInteger)) {
            userAtomicInteger = new AtomicInteger(0);
            passwordRetryCache.put(username, userAtomicInteger);
        }
        if (userAtomicInteger.getAndIncrement() > retryTimes) {
            throw new ExcessiveAttemptsException("超过最大的登陆次数,稍后再试");
        }

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,new String((char[]) token.getCredentials()));
        boolean matchs =  super.doCredentialsMatch(usernamePasswordToken,info);
        if (matchs) {
            passwordRetryCache.remove(username);
        } else {
            passwordRetryCache.put(username, userAtomicInteger);
        }
        return matchs;
    }


}
